/**
 * @file Implements StateMap.
 * @author Zmei Zelen <zmei.zelen@gmail.com>
 */


function StateMap(id) {
    this.id = id;
    this.on = new EventSet();
    this.on.add('out');
    this.enabled = true;
    this.states = {};    
}
;


StateMap.prototype.source = function(source, map) {
    source.on.out((function(command) {        
        command = Utils.copy(command);           
        if (!this.enabled) return;        
        if (map !== undefined) command.which = map[command.which];                
        if (command.which !== undefined) this.process(command);        
    }).bind(this));
};


StateMap.prototype.get = function(command) {
    if (typeof command !== 'object') {
        return this.states[command];
    } else {
        return this.states[command.which];
    }
};


StateMap.prototype.process = function(command) {
    if (Boolean(this.states[command.which]) !== command.state) {
        this.states[command.which] = command.state;        
        this.on.fire('out', command);        
    }
};


StateMap.prototype.set = function(which) {
    this.process({which: which, state: true, time: new Date().getTime()});        
};


StateMap.prototype.clear = function(which) {
    this.process({which: which, state: false, time: new Date().getTime()});        
};


StateMap.prototype.enable = function() {
    this.enabled = true;    
};



StateMap.prototype.disable = function(hard) {
    this.enabled = false;
    if (hard) {
        this.states = {};
    } else {
        for (var which in this.states) {
            this.clear(which);
        }
    }
};